<template>
  <!--  投诉和反馈-->
  <div class="feedback" :style="{ paddingTop: capsuleTop + 'px' }">
    <Return />
    <div class="feedback-box-class">
      <div class="feedback-box-class-title">
        问题类型
      </div>
      <div class="feedback-box-class-content">
        <div
          class="left"
          :class="{ active: questionType === 1 }"
          @click="selectFeedbackType(1)"
        >
          产品改进
        </div>
        <div
          class="right"
          :class="{ active: questionType === 2 }"
          @click="selectFeedbackType(2)"
        >
          功能异常
        </div>
      </div>
    </div>
    <!-- 订单信息选择 -->
    <!-- <div class="feedback-box-info" @click="showOrderPicker = true">
      <div class="feedback-label">订单信息</div>
      <div class="feedback-value">{{ selectedOrder ? selectedOrder.orderNo : '选择订单信息' }}</div>
    </div> -->

    <div class="feedback-box-info-box">
      <div class="feedback-box-info-item">
        <div class="feedback-label">姓名</div>
        <div class="feedback-value">
          <wd-input
            type="text"
            v-model="formData.name"
            placeholder="请输入用户名"
            @change="handleNameChange"
          />
        </div>
      </div>
      <div class="feedback-box-info-item" style="border-bottom: none;">
        <div class="feedback-label">手机号</div>
        <div class="feedback-value">
          <wd-input
            type="number"
            v-model="formData.phone"
            placeholder="请输入手机号"
            @change="handlePhoneChange"
          />
        </div>
      </div>
    </div>

    <div class="feedback-box-class-textarea" style="margin-top: 20rpx;">
      <div class="feedback-box-class-title">
        反馈内容
      </div>
      <wd-textarea
        v-model="formData.feedback"
        placeholder="请填写反馈内容"
        :maxlength="500"
        show-word-limit
      />
    </div>

    <div class="feedback-box-class-textarea" style="margin-top: 20rpx;">
      <div class="feedback-box-class-title">
        反馈图片
      </div>
      <div class="native-uploader">
        <div
          v-for="(file, idx) in fileList"
          :key="file.url || file.tempFilePath || idx"
          class="img-item"
          @click="previewImage(idx)"
        >
          <image :src="file.url || file.tempFilePath" mode="aspectFill" class="img" />
          <div class="del" @click.stop="deleteImage(idx)">×</div>
        </div>
        <div
          class="add-btn"
          v-if="fileList.length < maxCount"
          @click="chooseAndUpload"
        >
          <text class="add-icon">+</text>
          <text class="add-text">上传图片</text>
        </div>
      </div>
      <div class="upload-hint">最多上传 {{ maxCount }} 张，支持 jpg/png</div>
    </div>

    <div
      class="feedback-box-class-submit"
      :class="{ disabled: !canSubmit }"
      @click="handleSubmit"
    >
      {{ isSubmitting ? '提交中...' : '提交' }}
    </div>

    <!-- 订单选择弹窗 -->
    <wd-popup v-model="showOrderPicker" position="bottom" :close-on-click-modal="true">
      <div class="order-picker">
        <div class="order-picker-header">
          <span>选择订单</span>
          <span @click="showOrderPicker = false">关闭</span>
        </div>
        <div class="order-picker-content">
          <div
            v-for="order in orderList"
            :key="order.id"
            class="order-item"
            @click="selectOrder(order)"
          >
            <div class="order-info">
              <div class="order-no">订单号：{{ order.orderNo }}</div>
              <div class="order-time">{{ order.createTime }}</div>
            </div>
            <div class="order-status">{{ order.status }}</div>
          </div>
        </div>
      </div>
    </wd-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { baseUrl } from '@/utils/config'
import { useLoginStore } from '@/stores/login.js'
import Return from '@/components/Return.vue'
import { Fetch } from '@/composables/useFetch'

const capsuleTop = ref(0)
const questionType = ref(1) // 问题类型：1-产品改进, 2-功能异常
const showOrderPicker = ref(false)
const isSubmitting = ref(false)

// 表单数据
const formData = ref({
  name: '',      // 姓名
  phone: '',     // 手机号
  feedback: ''   // 反馈内容
})

// 反馈类型：1=产品改进，2=功能异常

// 其他相关变量
const fileList = ref([])
const selectedOrder = ref(null)

// 选中的订单
const orderList = ref([
  {
    id: '1',
    orderNo: 'ORD20231201001',
    createTime: '2023-12-01 10:30:00',
    status: '已完成'
  },
  {
    id: '2',
    orderNo: 'ORD20231202001',
    createTime: '2023-12-02 14:20:00',
    status: '进行中'
  }
])

// 原生上传配置
const maxCount = 5
const uploadUrl = `${baseUrl}shopping/sysFile/upload`
const loginStore = useLoginStore()

// 计算属性：是否可以提交
const canSubmit = computed(() => {
  return formData.value.name.trim() &&
         formData.value.phone.trim() &&
         formData.value.feedback.trim() &&
         !isSubmitting.value
})

// 选择反馈类型
const selectFeedbackType = (type) => {
  questionType.value = type
}

// 处理姓名和手机号输入（如有需要）
const handleNameChange = (val) => {
  formData.value.name = val
}
const handlePhoneChange = (val) => {
  formData.value.phone = val
}

// 原生上传：选择并上传
const chooseAndUpload = () => {
  const remain = maxCount - fileList.value.length
  if (remain <= 0) return
  uni.chooseImage({
    count: remain,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const paths = res.tempFilePaths || res.tempFiles?.map(f => f.path) || []
      for (const p of paths) {
        await uploadSingle(p)
      }
    }
  })
}

const uploadSingle = (filePath) => {

  return new Promise((resolve) => {
    uni.showLoading({ title: '上传中', mask: true })
    uni.uploadFile({
      url: uploadUrl,
      filePath,
      name: 'file',
      formData: {},
      header: {
        'accesstoken': loginStore.token || ''
      },
      success: (res) => {
        try {
          const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
          const url = data?.data?.fileUrl || data?.data || data?.fileUrl
          if (!url) throw new Error('未获取到文件地址')
          fileList.value.push({ url })
        } catch (e) {
          uni.showToast({ title: '上传失败，请重试', icon: 'none' })
        }
      },
      fail: () => {
        uni.showToast({ title: '上传失败，请检查网络', icon: 'none' })
      },
      complete: () => {
        uni.hideLoading()
        resolve()
      }
    })
  })
}

const deleteImage = (index) => {
  fileList.value.splice(index, 1)
}

const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: fileList.value.map(i => i.url || i.tempFilePath)
  })
}

// 选择订单
const selectOrder = (order) => {
  selectedOrder.value = order
  formData.value.orderId = order.id
  showOrderPicker.value = false
}

// 表单重置
const resetForm = () => {
  formData.value = {
    name: '',
    phone: '',
    feedback: ''
  }
  questionType.value = 1
  fileList.value = []
  selectedOrder.value = null
}

// 提交反馈
const handleSubmit = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  isSubmitting.value = true

  try {
    // 构建提交数据
    const submitData = {
      name: formData.value.name,
      phone: formData.value.phone,
      feedback: formData.value.feedback,
      questionType: questionType.value, // 1=产品改进，2=功能异常
      images: JSON.stringify(fileList?.value?.map(file => file.url)),
    }

    console.log('提交的数据：', submitData)

    // 调用接口
    const res = await Fetch('shopping/feedback/add', {
      method: 'POST',
      data: {
        ...submitData,
      }
    })
    console.log('res', res)
    if (res.data.code === 200) {
      uni.showToast({
        title: '反馈提交成功',
        icon: 'success'
      })
      resetForm()
    } else {
      uni.showToast({
        title: res.data?.msg || '提交失败，请重试',
        icon: 'none'
      })
    }

  } catch (error) {
    console.error('提交失败：', error)
    uni.showToast({
      title: error.message || '提交失败，请重试',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}

onMounted(() => {
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
})
</script>

<style lang="scss">
page {
  background: #F5F5F5;
}

.feedback {
  padding: 0 40rpx;

  .feedback-box-class,
  .feedback-box-class-textarea {
    width: 670rpx;
    height: 214rpx;
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    padding: 24rpx;
    box-sizing: border-box;

    .feedback-box-class-title {
      font-weight: bold;
      font-size: 28rpx;
      color: #191919;
      line-height: 40rpx;
      font-style: normal;
      text-transform: none;
    }
  }

  .feedback-box-class-content {
    margin-top: 30rpx;
    width: 622rpx;
    height: 90rpx;
    background: #F5F5F5;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    padding: 10rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;

    .left,
    .right {
      width: 302rpx;
      height: 70rpx;
      line-height: 70rpx;
      text-align: center;
      font-weight: bold;
      font-size: 24rpx;
      color: #191919;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      cursor: pointer;
      transition: all 0.3s ease;

      &.active {
        background: #FFFFFF;
      }
    }
  }

  .feedback-box-info {
    width: 670rpx;
    height: 88rpx;
    background: #FFFFFF;
    margin-top: 20rpx;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    display: flex;
    align-items: center;
    padding: 24rpx;
    box-sizing: border-box;
    cursor: pointer;
  }

  .feedback-box-info-box {
    width: 670rpx;
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 0 24rpx;
    box-sizing: border-box;
    border-radius: 20rpx 20rpx 20rpx 20rpx;

    .feedback-box-info-item {
      display: flex;
      align-items: center;
      padding: 26rpx 0;
      border-bottom: 2rpx solid #F1F1F2;
    }
  }

  .feedback-box-class-textarea {
    height: auto;
  }

  .feedback-box-class-submit {
    width: 670rpx;
    height: 100rpx;
    background: #FBE050;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
    font-size: 28rpx;
    color: #333333;
    font-weight: bold;
    text-align: center;
    line-height: 100rpx;
    margin-top: 30rpx;
    cursor: pointer;
    transition: all 0.3s ease;

    &.disabled {
      background: #CCCCCC;
      color: #999999;
      cursor: not-allowed;
    }
  }
}

.feedback-label {
  font-weight: bold;
  font-size: 28rpx;
  color: #191919;
  line-height: 40rpx;
  font-style: normal;
  text-transform: none;
}

.feedback-value {
  font-size: 28rpx;
  color: #999999;
  line-height: 40rpx;
  font-style: normal;
  text-transform: none;
  margin-left: auto;
}

// 订单选择器样式
.order-picker {
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;

  .order-picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 30rpx;
    border-bottom: 2rpx solid #F1F1F2;
    font-size: 32rpx;
    font-weight: bold;

    span:last-child {
      color: #999999;
      cursor: pointer;
    }
  }

  .order-picker-content {
    max-height: 600rpx;
    overflow-y: auto;
    padding-top: 30rpx;

    .order-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 2rpx solid #F1F1F2;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      .order-info {
        .order-no {
          font-size: 28rpx;
          color: #191919;
          margin-bottom: 10rpx;
        }

        .order-time {
          font-size: 24rpx;
          color: #999999;
        }
      }

      .order-status {
        font-size: 24rpx;
        color: #FBE050;
        background: rgba(251, 224, 80, 0.1);
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
      }
    }
  }
}

::v-deep {
  .wd-textarea {
    background: #F1F1F1 !important;
    border-radius: 20rpx !important;
    padding: 0 !important;
    margin-top: 26rpx;

    .wd-textarea__value {
      background: none !important;
    }

    .wd-textarea__inner {
      padding: 24rpx !important;
    }
  }

  .wd-upload {
    margin-top: 30rpx;
  }

  .wd-input {
    &::after {
      display: none !important;
    }

    .wd-input__inner {
      text-align: right;
      font-size: 28rpx;
      color: #999999;
    }
  }
}

.native-uploader {
  display: flex;
  flex-wrap: wrap;
  margin-top: 30rpx;

  .img-item,
  .add-btn {
    width: 210rpx;
    height: 210rpx;
    border-radius: 16rpx;
    background: #F5F5F5;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
  }

  .img-item:nth-child(3n) {
    margin-right: 0;
  }

  .img-item {
    position: relative;

    .img {
      width: 100%;
      height: 100%;
    }

    .del {
      position: absolute;
      top: 8rpx;
      right: 8rpx;
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
      border-radius: 50%;
      background: rgba(0,0,0,0.5);
      color: #fff;
      font-size: 28rpx;
    }
  }

  .add-btn {
    border: 2rpx dashed #dcdcdc;
    background: #fafafa;
    color: #999999;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .add-icon {
      font-size: 56rpx;
      line-height: 64rpx;
    }

    .add-text {
      margin-top: 8rpx;
      font-size: 24rpx;
      color: #b2b2b2;
    }
  }
}

.upload-hint {
  margin-top: 10rpx;
  font-size: 22rpx;
  color: #b2b2b2;
}
</style>
